﻿using System.IO;
using System.Text;
using UnityEngine;

namespace CGF
{
    public class StreamingAssetsHelper
    {
        private static AndroidJavaClass jc;

        /// <summary>
        /// 读取文本文件内容
        /// </summary>
        /// <param name="filePath">StreamingAssets目录下的路径</param>
        public static async CTask<string> GetText(string filePath)
        {
            byte[] bytes = await GetBytes(filePath);
            if (bytes != null)
            {
                return Encoding.UTF8.GetString(bytes);
            }
            return null;
        }

        /// <summary>
        /// 读取StreamingAssets目录下的数据
        /// </summary>
        /// <param name="filePath">StreamingAssets目录下的路径</param>
        public static async CTask<byte[]> GetBytes(string filePath)
        {
            if (Application.isEditor)
            {
                string path = Application.streamingAssetsPath + "/" + filePath;
                if (!File.Exists(path)) return null;
                return File.ReadAllBytes(path);
            }
            if (Application.platform == RuntimePlatform.IPhonePlayer)
            {
                string path = Application.dataPath + "/Raw/" + filePath;
                if (!File.Exists(path)) return null;
                return File.ReadAllBytes(path);
            }
            if (Application.platform == RuntimePlatform.Android)
            {
                if (jc == null) jc = new AndroidJavaClass("cn.helper.StreamingAssetsSync");
                return jc.CallStatic<byte[]>("getBytes", filePath);
            }
            if (Define.IsWebGL)
            {
                string path = Application.streamingAssetsPath + "/" + filePath;
                using (UnityEngine.Networking.UnityWebRequest request = UnityEngine.Networking.UnityWebRequest.Get(path))
                {
                    await request.SendWebRequest();
                    if (request.error != null)
                    {
                        return null;
                    }
                    else
                    {
                        return request.downloadHandler.data;
                    }
                }
            }
            return null;
        }
    }
}
